package com.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet Filter implementation class CharEncode
 */
public class CharEncode implements Filter {

	protected String encoding = null;
	   
    protected FilterConfig filterConfig = null;

    protected boolean ignore = true;

    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
	
	/**
     * Default constructor. 
     */
    public CharEncode() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		  if (ignore || (request.getCharacterEncoding() == null)) {
	            String encoding = selectEncoding(request);
	            if (encoding != null) {
	                request.setCharacterEncoding(encoding);
	            }
	        } 
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("filter init");
		  this.filterConfig = fConfig;
	       this.encoding = filterConfig.getInitParameter("Encoding");//从web.xml文件中读到参数
	       System.out.println(this.encoding);
	        String value = filterConfig.getInitParameter("ignore");
	        if (value == null) {
	            this.ignore = true;
	        } else if (value.equalsIgnoreCase("true")) {
	            this.ignore = true;
	        } else if (value.equalsIgnoreCase("yes")) {
	            this.ignore = true;
	        } else {
	            this.ignore = false;
	        }
		
		System.out.println("filter init finished");
	}
	 protected String selectEncoding(ServletRequest request) {
	        return (this.encoding);
	    }

}
